package net.kazed.nextaction.task;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.kazed.nextaction.database.TaskAttachmentList;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.text.util.Linkify;
import android.widget.TextView;
import android.widget.Toast;

public class BarCodeAttachmentType extends AttachmentType {
    
    /**
     * @param labelResource Resource of label string.
     * @param requestCode Unique code for request.
     */
    public BarCodeAttachmentType(int labelResource, int requestCode) {
        super(labelResource, requestCode);
    }

    /**
     * @return Intent for attachment type.
     */
    public Intent getIntent() {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
        return intent;
    }

    @Override
    public void addAttachment(Context context, ContentResolver contentResolver, Intent data, TaskAttachmentList attachmentList) {
        String contents = data.getStringExtra("SCAN_RESULT");
        String format = data.getStringExtra("SCAN_RESULT_FORMAT");
        // Handle successful scan
        Toast.makeText(context, "barcode: " + contents + ", " + format, Toast.LENGTH_LONG).show();
    }

    @Override
    public String getAttachmentLink(Context context, Intent data) {
        String contents = data.getStringExtra("SCAN_RESULT");
        String format = data.getStringExtra("SCAN_RESULT_FORMAT");
        // Handle successful scan
        StringBuilder builder = new StringBuilder("barcode://");
        builder.append(format).append("/").append(contents);
        return builder.toString();
    }
    
   
    public void addLinks(TextView view) {
        final Pattern bookMatcher = Pattern.compile("\\bbarcode\\://EAN_13/978([A-Za-z0-9]+)\\b");
        Linkify.MatchFilter matchFilter = new Linkify.MatchFilter() {
            public boolean acceptMatch(CharSequence s, int start, int end) {
                return bookMatcher.matcher(s.subSequence(start, end)).matches();
            }
            
        };
        Linkify.TransformFilter transformFilter = new Linkify.TransformFilter() {
            public String transformUrl(Matcher match, String url) {
                return match.group(1);
            }
            
        };
        
        
        String bookUrl = "http://www.amazon.com/dp/";
//        Linkify.addLinks(view, bookMatcher, bookUrl);
        
        Linkify.addLinks(view, bookMatcher, bookUrl, matchFilter, transformFilter);
    }

}
